<template>
  <div class="sidebar-container">
    <div class="sidebar-header">
      <h3>我的列表</h3>
      <el-button 
        type="primary" 
        :icon="Plus" 
        circle 
        size="small" 
        @click="showAddListModal"
        title="创建新列表"
      />
    </div>
    <el-menu
      :default-active="currentListId"
      class="el-menu-vertical-demo"
      @select="handleSelect"
    >
      <el-menu-item 
        v-for="list in lists" 
        :key="list.id" 
        :index="list.id"
        class="list-item"
      >
        <el-icon><document /></el-icon>
        <span>{{ list.name }}</span>
        <el-popconfirm
          title="确定要删除这个列表吗？"
          @confirm="() => deleteList(list.id)"
        >
          <template #reference>
            <el-button 
              type="danger" 
              :icon="Delete" 
              circle 
              size="small" 
              class="delete-btn"
            />
          </template>
        </el-popconfirm>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script lang="ts" setup>
import { Document, Plus, Delete } from '@element-plus/icons-vue'
import { computed } from 'vue'
import { useListStore } from '@/store/list'
import { useTaskStore } from '@/store/task'

const listStore = useListStore()
const taskStore = useTaskStore()

const lists = computed(() => listStore.getLists)
const currentListId = computed(() => taskStore.currentListId)

const handleSelect = (index: string) => {
  taskStore.setCurrentListId(index)
}

const showAddListModal = () => {
  // 触发父组件显示添加列表模态框
  window.dispatchEvent(new CustomEvent('show-add-list-modal'))
}

const deleteList = async (id: string) => {
  try {
    await listStore.deleteList(id)
    // 如果删除的是当前选中的列表，清除当前列表ID
    if (currentListId.value === id) {
      taskStore.setCurrentListId(null)
    }
  } catch (error) {
    console.error('删除列表失败:', error)
  }
}
</script>

<style scoped>
.sidebar-container {
  width: 100%;
  height: 100%;
  background-color: #f0f9eb;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
}

.sidebar-header h3 {
  margin: 0;
  color: #67c23a;
}

.el-menu-vertical-demo {
  flex: 1;
  overflow-y: auto;
  width: 100% !important;
  border-right: none;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 100% !important;
  min-height: auto;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.list-item:hover .delete-btn {
  opacity: 1;
}
</style>
